package com.jiaquyun.jcyx.main.goods

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ConvertUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.CartAction
import com.jiaquyun.jcyx.entity.GoodsGroup
import com.jiaquyun.jcyx.main.goods.adapter.GoodsListAdapter
import com.jiaquyun.jcyx.jetpack.mode.GoodsViewModel
import com.jiaquyun.jcyx.utils.JsonUtils
import com.module.lemlin.custom.SpacingItemDecoration
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.image.loadCenterImage
import com.module.lemlin.owner.OwnerViewModeActivity
import kotlinx.android.synthetic.main.activity_goods_active.*
import java.io.Serializable

class GoodsActiveActivity : OwnerViewModeActivity<GoodsViewModel>() {

    data class GoodsActiveValue(
        val id: Int,
        val title: String,
        val image: String
    ) : Serializable

    companion object {
        private const val KEY_GOODS_ACTIVITY = "KEY_GOODS_ACTIVITY"
        fun open(activity: Activity, goodsActivity: GoodsActiveValue) {
            val intent = Intent(activity, GoodsActiveActivity::class.java)
            intent.putExtra(KEY_GOODS_ACTIVITY, goodsActivity)
            activity.startActivity(intent)
        }
    }

    private val mGoodsActiveValue: GoodsActiveValue?
        get() = intent?.getSerializableExtra(KEY_GOODS_ACTIVITY) as? GoodsActiveValue

    private val goodsListAdapter: GoodsListAdapter = GoodsListAdapter()

    override fun viewModel(): GoodsViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_goods_active

    override fun stateBar(): StatusBar {
        return StatusBar(color = R.color.colorWhite, view = flGoodsActiveBar)
    }

    override fun initView() {

        ivAppBack.setOnClickListener { finish() }
        rvGoodsActiveBody.apply {
            val decoration = SpacingItemDecoration(
                vGap = ConvertUtils.dp2px(13f),
                hGap = ConvertUtils.dp2px(13f),
                isHead = true
            )
            addItemDecoration(decoration)
            itemAnimator?.changeDuration = 0
        }.adapter = goodsListAdapter
        goodsListAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData: GoodsGroup = goodsListAdapter.data[position]
            if (view.id == R.id.ivGoodsPlus) {
                val num: Int = itemData.cart_num + 1
                if (itemData.cart_id == 0 || itemData.cart_num == 0) {
                    viewModel.cartAdd1(itemData.id, num)
                } else {
                    viewModel.cartChangeNum1(itemData.id, itemData.cart_id, num)
                }
            }
            if (view.id == R.id.ivGoodsMinus) {
                val num: Int = itemData.cart_num - 1
                if (num == 0) {
                    viewModel.cartRemove(itemData.id, itemData.cart_id)
                } else {
                    viewModel.cartChangeNum1(itemData.id, itemData.cart_id, num)
                }
            }
        }
    }


    override fun initData() {
        mGoodsActiveValue?.let {
            viewModel.goodsActivity(it.id)
            goodsListAdapter.setHeaderView(createHeadsView().apply {
                loadCenterImage(it.image)
            })
            tvGoodsActiveTitle.text = it.title
        }
    }

    override fun initViewMode() {

        viewModel.goodsActiveLiveData.observe(this, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.data?.let {
                val goodsGroups:MutableList<GoodsGroup> = try {
                    JsonUtils.stringToList(it.goods_group,GoodsGroup::class.java)
                }catch (e:Exception) {
                    mutableListOf<GoodsGroup>()
                }
                fillData(goodsGroups)
            }
        })

        //监听购物车添加
        viewModel.cartAdd1LiveData.observe(this, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车加减
        viewModel.cartChangeNum1LiveData.observe(this, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车删除
        viewModel.cartDelete1LiveData.observe(this, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.status.desc)
            }
        })
    }

    override fun onEventMainThread(any: Any) {
        if (any !is CartAction)
            return
        if (any.action == CartAction.Action.CLEAR) {
            val position = mutableListOf<Int>()
            for ((index, item) in goodsListAdapter.data.withIndex()) {
                if (item.cart_num != 0) position.add(index)
            }
            position.forEach {
                goodsListAdapter.setData(it)
            }
        } else {
            val position = goodsListAdapter.data.indexOfFirst {
                it.id == any.goodsId
            }
            if (position == -1)
                return
            goodsListAdapter.setData(position, any.goodsNum, any.cartId)
        }
    }

    private fun fillData(goodsGroup: MutableList<GoodsGroup>) {
        goodsListAdapter.setNewInstance(goodsGroup)
    }

    private fun createHeadsView(): ImageView = ImageView(this as Context).apply {
        layoutParams = FrameLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        adjustViewBounds = true
    }

}